package com.bdk.middle.management.web;

import com.bdk.middle.common.result.ResultDO;
import com.bdk.middle.common.result.web.ObjectResponse;
import com.bdk.middle.management.api.domain.AdminDO;
import com.bdk.middle.management.api.domain.MenuDO;
import com.bdk.middle.management.api.domain.RoleDO;
import com.bdk.middle.management.service.PermissionService;
import com.bdk.middle.management.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @Author: chang
 * 系统菜单控制器
 */

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    /**
     * 用户系统菜单列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/list.html", method = RequestMethod.POST)
    @PreAuthorize("hasRole('ROLE_superadmin')")
    public ObjectResponse menuList(){
        ObjectResponse response = new ObjectResponse();
        //当前用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        //系统用户角色id集
        ResultDO result=roleService.getRoleIdsByUsername(username);
        if(!result.isSuccess()) {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }else {

        }
        Set<String>  roleIds=(Set<String>)result.getModel(ResultDO.FIRST_MODEL_KEY);
        //返回角色相应的菜单
        List<MenuDO> menus=null;
        for(String roleId:roleIds){
            menus= permissionService.getMenusByRoleId(roleId);
        }
        response.setData(menus);
        return response;
    }
}
